<template>
  <div class="login-container">
    <div class="login-box">
      <h2 style="color:darkblue">学生作业管理系统</h2>
      <div class="role-selector">
        <el-radio-group v-model="loginType">
          <el-radio-button label="admin">管理员</el-radio-button>
          <el-radio-button label="teacher">教师</el-radio-button>
          <el-radio-button label="student">学生</el-radio-button>
        </el-radio-group>
      </div>
      <div class="login-form">
        <!-- 用户名输入框 -->
        <el-input 
          placeholder="请输入账号" 
          v-model="username"
          prefix-icon="el-icon-user"
          style="margin-bottom: 15px;">
        </el-input>
        <!-- 密码输入框 -->
        <el-input 
          placeholder="请输入密码" 
          v-model="password"
          show-password
          prefix-icon="el-icon-lock"
          style="margin-bottom: 20px;">
        </el-input>
        <!-- 登录按钮 -->
        <el-button type="primary" @click="handleLogin" style="width: 100%;" :loading="loading">登录</el-button>
        <!-- 学生注册按钮 -->
        <el-button 
          v-if="loginType === 'student'" 
          type="text" 
          @click="showRegisterDialog" 
          style="margin-top: 10px;">
          还没有账号？立即注册
        </el-button>
        <!-- 占位按钮，保持高度一致 -->
        <el-button 
          v-else
          type="text" 
          style="margin-top: 10px; visibility: hidden;">
          占位
        </el-button>
      </div>
    </div>

    <!-- 学生注册对话框 -->
    <el-dialog 
      title="学生注册" 
      :visible.sync="registerDialog.visible" 
      width="500px"
      :close-on-click-modal="false">
      <el-form 
        :model="registerForm" 
        :rules="registerRules" 
        ref="registerForm" 
        label-width="100px">
        <!-- 姓名输入框 -->
        <el-form-item label="姓名" prop="name">
          <el-input v-model="registerForm.name" placeholder="请输入姓名"></el-input>
        </el-form-item>
        
        <!-- 性别选择 -->
        <el-form-item label="性别" prop="gender">
          <el-radio-group v-model="registerForm.gender">
            <el-radio label="男">男</el-radio>
            <el-radio label="女">女</el-radio>
          </el-radio-group>
        </el-form-item>
        
        <!-- 入学年份选择 -->
        <el-form-item label="入学年份" prop="year">
          <el-select v-model="registerForm.year" placeholder="请选择入学年份" style="width: 100%" @change="handleYearChange">
            <el-option v-for="year in yearOptions" :key="year" :label="`${year}年`" :value="year"></el-option>
          </el-select>
        </el-form-item>
        <!-- 院系选择 -->
        <el-form-item label="所属院系" prop="deptNumber">
          <el-select v-model="registerForm.deptNumber" placeholder="请选择所属院系" style="width: 100%" @change="handleDeptChange">
            <el-option
              v-for="dept in departments"
              :key="dept.deptNumber"
              :label="dept.deptName"
              :value="dept.deptNumber">
            </el-option>
          </el-select>
        </el-form-item>
        <!-- 班级选择 -->
        <el-form-item label="所属班级" prop="classId">
          <el-select v-model="registerForm.classId" placeholder="请选择所属班级" style="width: 100%" :disabled="!registerForm.deptNumber" @change="generateStudentId">
            <el-option
              v-for="cls in classesByDept"
              :key="cls.classId"
              :label="cls.className"
              :value="cls.classId">
            </el-option>
          </el-select>
        </el-form-item>
        <!-- 自动生成的学号显示 -->
        <el-form-item label="学号" prop="studentId">
          <el-input v-model="registerForm.studentId" placeholder="将自动生成学号" disabled></el-input>
          <span class="form-tip">学号将根据入学年份、院系和班级自动生成</span>
        </el-form-item>
        <!-- 密码输入框 -->
        <el-form-item label="密码" prop="password">
          <el-input v-model="registerForm.password" type="password" placeholder="请输入密码"></el-input>
        </el-form-item>
        <!-- 确认密码输入框 -->
        <el-form-item label="确认密码" prop="confirmPassword">
          <el-input v-model="registerForm.confirmPassword" type="password" placeholder="请再次输入密码"></el-input>
        </el-form-item>
        <!-- 邮箱输入框 -->
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="registerForm.email" placeholder="请输入邮箱"></el-input>
        </el-form-item>
        <!-- 手机号输入框 -->
        <el-form-item label="手机号" prop="phone">
          <el-input v-model="registerForm.phone" placeholder="请输入手机号"></el-input>
        </el-form-item>
      </el-form>
      <!-- 对话框底部按钮 -->
      <span slot="footer" class="dialog-footer">
        <el-button @click="registerDialog.visible = false">取 消</el-button>
        <el-button type="primary" @click="handleRegister">注 册</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import { adminLogin, teacherLogin, studentLogin, studentRegister } from '@/api/auth'
import { getAllDepartments, getClassesByDepartment, getStudentCountByClassId } from '@/api/admin'

export default {
  name: 'LoginPage',
  data() {
    // 密码确认验证
    const validateConfirmPassword = (rule, value, callback) => {
      if (value !== this.registerForm.password) {
        callback(new Error('两次输入的密码不一致'))
      } else {
        callback()
      }
    }
    return {
      loginType: 'student', // 默认选中的角色
      username: '',         // 用户名
      password: '',         // 密码
      loading: false,       // 加载状态
      // 注册对话框数据
      registerDialog: {
        visible: false
      },
      // 年份选项
      yearOptions: [2024, 2023, 2022, 2021],
      // 院系列表
      departments: [],
      // 按院系筛选的班级列表
      classesByDept: [],
      // 注册表单数据
      registerForm: {
        studentId: '',
        name: '',
        gender: '男', // 默认值
        year: '',
        deptNumber: '',
        classId: '',
        password: '',
        confirmPassword: '',
        email: '',
        phone: ''
      },
      // 注册表单验证规则
      registerRules: {
        name: [
          { required: true, message: '请输入姓名', trigger: 'blur' }
        ],
        gender: [
          { required: true, message: '请选择性别', trigger: 'change' }
        ],
        year: [
          { required: true, message: '请选择入学年份', trigger: 'change' }
        ],
        deptNumber: [
          { required: true, message: '请选择所属院系', trigger: 'change' }
        ],
        classId: [
          { required: true, message: '请选择所属班级', trigger: 'change' }
        ],
        studentId: [
          { required: true, message: '学号不能为空', trigger: 'blur' }
        ],
        password: [
          { required: true, message: '请输入密码', trigger: 'blur' },
          { min: 6, message: '密码长度不能小于6位', trigger: 'blur' }
        ],
        confirmPassword: [
          { required: true, message: '请再次输入密码', trigger: 'blur' },
          { validator: validateConfirmPassword, trigger: 'blur' }
        ],
        email: [
          { required: true, message: '请输入邮箱', trigger: 'blur' },
          { type: 'email', message: '请输入正确的邮箱地址', trigger: 'blur' }
        ],
        phone: [
          { required: true, message: '请输入手机号', trigger: 'blur' },
          { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号码', trigger: 'blur' }
        ]
      }
    }
  },
  methods: {
    // 处理登录
    handleLogin() {
      if (!this.username || !this.password) {
        this.$message.error('账号和密码不能为空');
        return;
      }
      
      // 设置加载状态
      this.loading = true;
      
      // 根据登录类型调用不同的登录API
      let loginRequest;
      if (this.loginType === 'admin') {
        loginRequest = adminLogin(this.username, this.password);
      } else if (this.loginType === 'teacher') {
        loginRequest = teacherLogin(this.username, this.password);
      } else {
        loginRequest = studentLogin(this.username, this.password);
      }
      
      // 处理登录响应
      loginRequest.then(response => {
        if (response.code === 200) {
          // 登录成功
          const data = response.data;
          // 保存token和用户信息
          localStorage.setItem('token', data.token);
          localStorage.setItem('userInfo', JSON.stringify(data.userInfo));
          
          // 更新Vuex状态
          this.$store.dispatch('setUserInfo', data.userInfo);
          
          // 根据角色类型跳转到不同页面
          const roleRoutes = {
            admin: '/admin/dashboard',
            teacher: '/teacher/classes',
            student: '/student/dashboard'
          };
          this.$router.push(roleRoutes[this.loginType]);
          this.$message.success('登录成功');
        } else {
          // 登录失败
          this.$message.error(response.message || '登录失败');
        }
      }).catch(error => {
        console.error('登录错误:', error);
        this.$message.error('登录异常，请稍后重试');
      }).finally(() => {
        this.loading = false;
      });
    },
    
    // 显示注册对话框
    showRegisterDialog() {
      this.registerDialog.visible = true
      this.registerForm = {
        studentId: '',
        name: '',
        gender: '男', // 默认选择"男"
        year: 2024, // 默认选中2024年
        deptNumber: '',
        classId: '',
        password: '',
        confirmPassword: '',
        email: '',
        phone: ''
      }
      // 加载院系列表
      this.loadDepartments()
    },
    
    // 加载院系列表
    loadDepartments() {
      getAllDepartments().then(response => {
        if (response.code === 200) {
          this.departments = response.data
        } else {
          this.$message.error('获取院系列表失败')
        }
      }).catch(error => {
        console.error('获取院系列表错误:', error)
        this.$message.error('获取院系列表异常')
      })
    },
    
    // 院系变更处理
    handleDeptChange() {
      this.registerForm.classId = '' // 清空班级选择
      this.registerForm.studentId = '' // 清空自动生成的学号
      
      if (!this.registerForm.deptNumber) {
        this.classesByDept = []
        return
      }
      
      // 加载该院系下的班级列表
      getClassesByDepartment(this.registerForm.deptNumber).then(response => {
        if (response.code === 200) {
          // 如果选择了年级，只显示该年级的班级
          if (this.registerForm.year) {
            // 过滤出与选择年级相匹配的班级
            this.classesByDept = response.data.filter(cls => 
              cls.grade === this.registerForm.year.toString()
            )
            if (this.classesByDept.length === 0) {
              this.$message.warning(`该院系暂无${this.registerForm.year}年级的班级`)
            }
          } else {
            this.classesByDept = response.data
          }
        } else {
          this.$message.error('获取班级列表失败')
        }
      }).catch(error => {
        console.error('获取班级列表错误:', error)
        this.$message.error('获取班级列表异常')
      })
    },
    
    // 年级变更处理
    handleYearChange() {
      this.registerForm.classId = '' // 清空班级选择
      this.registerForm.studentId = '' // 清空自动生成的学号
      
      // 如果已经选择了院系，则重新加载对应年级的班级
      if (this.registerForm.deptNumber) {
        this.handleDeptChange()
      }
    },
    
    // 自动生成学号
    generateStudentId() {
      if (!this.registerForm.year || !this.registerForm.deptNumber || !this.registerForm.classId) {
        this.registerForm.studentId = ''
        return
      }
      
      // 找到所选班级的信息
      const selectedClass = this.classesByDept.find(cls => cls.classId === this.registerForm.classId)
      if (!selectedClass) {
        this.registerForm.studentId = ''
        return
      }
      
      // 获取班级学生数量，用于生成学号末尾的序号
      getStudentCountByClassId(this.registerForm.classId).then(response => {
        if (response.code === 200) {
          const studentCount = response.data
          
          // 生成学号：年份(后两位) + 学院编号(全部) + 专业编码(全部) + 班级号(2位) + 班级学生数量(从01开始)
          const yearPart = this.registerForm.year.toString().substring(2) // 年份后两位
          const deptPart = this.registerForm.deptNumber // 完整学院编号
          const majorPart = selectedClass.majorCode // 完整专业编码
          const classPart = selectedClass.classNumber.padStart(2, '0') // 班级号，补齐两位
          
          // 学生序号从01开始，所以当前数量+1
          const seqPart = (studentCount + 1).toString().padStart(2, '0')
          
          this.registerForm.studentId = yearPart + deptPart + majorPart + classPart + seqPart
        } else {
          this.$message.error('获取班级学生数量失败')
          this.registerForm.studentId = ''
        }
      }).catch(error => {
        console.error('获取班级学生数量错误:', error)
        this.$message.error('获取班级学生数量异常')
        this.registerForm.studentId = ''
      })
    },
    
    // 处理注册
    handleRegister() {
      // 检查学号是否已生成
      if (!this.registerForm.studentId) {
        this.$message.warning('请先选择入学年份、院系和班级，以生成学号')
        return
      }
      
      this.$refs.registerForm.validate(valid => {
        if (valid) {
          const { studentId, name, gender, password, email, phone, year, deptNumber, classId } = this.registerForm;
          
          // 调用注册API
          studentRegister({
            studentId,
            name,
            gender,
            password,
            email,
            phone,
            year,
            deptNumber,
            classId
          }).then(response => {
            if (response.code === 200) {
              // 注册成功
              this.$message.success('注册成功，请登录');
              this.registerDialog.visible = false;
              // 将注册的学号填入登录框
              this.username = studentId;
              this.password = '';
            } else {
              // 注册失败
              this.$message.error(response.msg || '注册失败');
            }
          }).catch(error => {
            console.error('注册错误:', error);
            this.$message.error('注册异常，请稍后重试');
          });
        }
      })
    }
  }
}
</script>

<style scoped>
.login-container {
  height: 100vh;
  display: flex;
  justify-content: center;
  align-items: center;
  background-image: url('../assets/login.jpg');/* 使用本地图片作为背景 */
  background-size: cover; /* 让背景图片覆盖整个容器 */
  background-position: center; /* 居中显示背景图片 */
}

.login-box {
  width: 400px;
  padding: 30px;
  background: #fff;
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
  min-height: 400px; /* 添加最小高度 */
  display: flex;
  flex-direction: column;
}

.login-box h2 {
  text-align: center;
  margin-bottom: 30px;
  color: #303133;
}

.role-selector {
  text-align: center;
  margin-bottom: 20px;
}

.login-form {
  display: flex;
  flex-direction: column;
  flex: 1; /* 让表单占据剩余空间 */
}

/* 注册按钮样式 */
.el-button--text {
  width: 100%;
  text-align: center;
  color: #409EFF;
}

/* 注册按钮悬停样式 */
.el-button--text:hover {
  color: #66b1ff;
}

/* 添加表单提示样式 */
.form-tip {
  color: #909399;
  font-size: 12px;
  line-height: 1;
  display: block;
  margin-top: 4px;
}
</style>